<template>
  <section class="bg-default video-page">
    <headerbar @onback="" class="no-bg header-wrap-wrap"></headerbar>

    <section class="no-shadow video-page-content">
      <div class="video">
        <div v-if="!isVideo" class="audio">
          <img class="audio-img" :src="getPoster(detail)" alt="" />
          <div class="audio-self">
            <audio
              id="myAudio"
              ref="myAudio"
              @ended="onended"
              controlsList="nodownload"
              loop="loop"
              :src="getVideoSrc(detail)"
              preload="auto"
              controls
              autoplay="autoplay"
            >
              您的浏览器不支持 audio 标签。
            </audio>
          </div>
        </div>
        <div class="inner" id="videoPlayer"></div>
        <!--<video v-if="detail.files && detail.files.length>0" :style="{height:'100%'}" :poster="getPoster(preData)" loop="loop" :src="getVideoSrc(detail)" preload="auto" controls autoplay="autoplay" x5-video-player-type="h5-page"></video>-->
      </div>
      <section class="detail">
        <h1 class="title">{{ preData.title }}</h1>
        <p class="date">
          <span class="flex-1">来源：{{ preData.source || "未知" }}</span>
          <span class="float-right">时间：{{ preData.createTime }}</span>
        </p>
        <p class="color-red pdh-2 pdv-1 shortTitle">{{ preData.shortTitle }}</p>
        <div
          class="text-wrap m-content overflow-line"
        >
          {{ preData.videoSummary }}

<!--          {{content}}-->
        </div>
        <div class="btn-more" v-if="getIsShow(preData.videoSummary)" @click="showmoreDesc($event)">展开</div>
        <p class="line"></p>
        <div
          class="cont-text cont-text-video"
          v-if="false && detail.newsContentExt"
          v-html="detail.newsContentExt.contents"
        ></div>
        <div v-if="!isComment" class="slider-my"></div>
        <div v-if="!isComment" class="pdv-10"></div>
        <div v-if="!isVideo && audioList && audioList.length >0" class="audio-list pdt-5 block">
          <div
            @click="playAudio(item)"
            :class="{ 'color-red': item.id == preData.id }"
            v-for="item in audioList"
            class="item"
          >
            <div class="title">{{ item.title }}</div>
            <div class="tip-wrap">
              <span class="play-tip">{{ item.views }}</span>
              <span class="time-tip">{{ item.createTime }}</span>
            </div>
          </div>
        </div>

        <p class="pdv-2"></p>
        <viewsUpsComponent v-if="detail.newsContentExt && isUpsComponent"></viewsUpsComponent>
        <p class="pdv-2"></p>
<!--        <div class="water-logo" v-if="!isComment">
          <img
            src="static/images/dangjian/home/water-logo-comment.png"
            alt=""
          />
          <div class="pdv-7"></div>
        </div>-->
        <section :class="[{'d-scroll-2head': isComment},{'d-scroll-3head': isInputFocus}]" style="height: 30vh">
          <commentListComponent
            @log="log"
            :key="preData.id"
            v-if="detail.newsContentExt && allowProhibit"
            :_contentId="preData.id"
            :isComment="isComment"
            :shareType="shareType" @onInputFocus="onInputFocus"
          ></commentListComponent>
        </section>
      </section>
    </section>
    <readScore
      ref="scoreInstance"
      v-if="detail.newsContent"
      :_contentId="detail.newsContent.id"
      :type="2"
    ></readScore>
  </section>
</template>

<script>
import _ from "lodash";
import commentListComponent from "@/components/common/commentListComponent";
import $ from "../../../../static/js/jquery-1.12.4.min";
import viewsUpsComponent from "@/components/common/viewsUpsComponent";
import domUtils from "@/utils/domUtils";
import Axios from "axios";
//  import Aliplayer from '../../../../static/js/lib/aliplayer-min'
//  let Aliplayer = require('../../../../static/js/lib/aliplayer-min')
let TEST = true; // 测试 阿里播放器
export default {
  components: { commentListComponent, viewsUpsComponent },
  name: "videoDetail",
  data() {
    return {
      preData: {},
      audioList: [],
      isVideo: true,
      clickPlay: false,
      shareType: 1,
      //控制超长隐藏显示
      isShowMore: false,
      isDescStatus: true,
      introduce: '',
      //控制超长隐藏显示
      detail: {
        newsContent: null,
        files: null,
        upOrDown: null,
        collected: null,
      },
      isComment:true,//是否允许评论 true 允许 false 不允许
      allowProhibit:true,//是否启用下方输入框 true 允许 false 不允许
      isUpsComponent:true,//是否展示点赞量和阅读量 true 展示 false 不展示,
      isInputFocus: false,
    };
  },
  created() {
    this.isComment = this.$route.params.isComment === false ? false : true
    this.isUpsComponent = this.$route.params.isUpsComponent === false ? false : true
    this.allowProhibit = this.$route.params.allowProhibit === false ? false : true
    this.init();
  },
  beforeDestroy() {
    this.log();
    clearInterval(this.checkPlayerTimer);
    this.$store.commit("setPLAY_BROADCAST",'');
  },
  methods: {
    getIsShow(content){
        if(content && content.length >= 40){
          return true;
        }
      return false;
    },
    //控制超长隐藏显示
    showmoreDesc(e) {
      let el = e.currentTarget;
      el.previousElementSibling.classList[!this.isDescStatus ? 'add' : 'remove']('overflow-line');
      el.classList[this.isDescStatus ? 'add' : 'remove']('more-collapse');
      el.innerHTML = !this.isDescStatus ? '展开' : '收起';
      this.isDescStatus = !this.isDescStatus;
      this.isShowMore = true;
    },
    onInputFocus(blo) {
      this.isInputFocus = blo;
    },
    init() {
      if (this.$route.query.zhuanji !== 1) {
        this.$store.state.zhuanjiList = [];
      }
      this.isVideo = this.$store.state.isVideo;
      // 0:新闻，1:视频；6:音频
      this.shareType = this.isVideo ? 1 : 6;
      this.$store.state.flagType = 2;
      this.preData = this.$store.state.videoDetail;
      this.updateCount();
      if (!this.isVideo) {
        this.audioList = this.$store.state.zhuanjiList;
        window.audioPlayer.hide();
      } else {
        window.audioPlayer.pause();
      }
      this.loadData();
    },
    // 添加到我的足迹
    historyAdd () {
      let data = {
        contentId: this.detail.newsContentExt.contentId,
        newsType: this.isVideo ? 1 : 2,  // 新闻类型(0图文;1长视频;2音频;3短视频)
      }
      this.fetchService.historyAdd(data).then((res) => {
      })
    },
    log(actionType) {
      let type = actionType || 5; //操作取值范围： 1 点赞、2 收藏、3 评论、4 转发、5 浏览
      console.log("type", type);
      this.logEvent(type, {
        //所有的标签都可以使用相对应的中文
        content_type: 1, //内容类型 1 文字、2 音频、3 视频
        area_type: this.preData.qyflTags || "", //区域分类 1 贵州省、2 贵阳市、3 观山湖区、4 南明区、5 云岩区、6 白云区、7 花溪区、8 乌当区、9 清镇市、10 开阳县、11 息烽县
        theme_type: this.preData.ztflTags || "", //主题分类 1 本地动态、2 政策解读、3 人事动态、4 警钟长鸣、5 党务知识、6 动态、7 示范带、8 身边好党员、9 党史上的今天
        event_type: this.preData.sjflTags || "", //事件分类 1 召开会议、2 考察调研、3 主持会议、4 致辞、5 出席、6 发展、7 发表、8 建设、9 讲话
        arrangement_type: this.preData.ccflTags || "", //层次分类 中央、省级、市级、区县级
        soure_type: this.preData.lyflTags || "", //来源分类 1 共产党员网、2 人民网、3 新华社、4 人民日报、5 贵州日报、6 贵阳日报、7 贵阳党建网、8 贵阳市政府网、9 贵阳市人力资源网、10天眼新闻、11 知知贵阳、12 贵州改革
        character_type: this.preData.rwflTags || "", //人物分类 1 习近平、2 李克强、3 孙志刚、4 谌贻琴、5 赵德明、6 陈晏、7 滕伟华
        other_type: 0, //其他分类
        category_type:this.preData.categoryTags || "",//分类 1 农村 2 城市社区 3 机关 4 学校 5 国有企业 6 非公有制经济组织和社会组织 7 其他
        content_id: this.preData.id, //内容ID
        content_title: this.preData.title, //内容标题
        publish_time: this.preData.publishTime,
      });
    },
    /*专辑播放音乐*/
    playAudio(item) {
      console.log("playAudio");
      if (!this.isVideo) {
        this.$store.state.zhuanjiList = JSON.parse(
          JSON.stringify(this.$store.state.zhuanjiList)
        );
      }
      this.clickPlay = true;
      this.$store.state.videoDetail = item;
      let routeName = this.$route.name;
      this.$router.replace({
        name: routeName,
        query: { id: item.id, zhuanji: 1 },
      });
      this.init();
    },
    /*播放下一首*/
    playAudioNext() {
      clearTimeout(this.$refs.myAudio.playAudioNextTimer);
      this.$refs.myAudio.playAudioNextTimer = setTimeout(() => {
        let playingIndex = this.audioList.findIndex((item) => {
          return item.id === this.preData.id;
        });
        let nextIndex = playingIndex + 1;
        console.log("playAudioNext", nextIndex);
        if (nextIndex >= this.audioList.length) {
          nextIndex = 0;
        }
        this.playAudio(this.audioList[nextIndex]);
      }, 1000);
    },
    /*音频播放完成*/
    audioEnded() {
      console.log("audioEnded");
      this.$refs.scoreInstance.getScore("read");
      this.playAudioNext();
    },
    /*视频播放完成*/
    onended() {
      if (!this.isVideo) {
        return this.audioEnded();
      }
      console.log("ended");
      this.$refs.scoreInstance.getScore("watch");
    },
    listenAudio() {
      // 如果是选择播放，监听事件不必反复执行
      if (this.clickPlay) {
        return false;
      }
      this.clickPlay = true;
      if (!this.isVideo) {
        this.$refs.myAudio.onended = () => {
          console.log("audio ended");
          this.onended();
        };
        let myAudio = document.getElementById("myAudio");
        myAudio.addEventListener("ended", () => {
          console.log("audio ended");
          this.onended();
        });
        myAudio.addEventListener("timeupdate", (e) => {
          console.log("timeupdate");
          if (myAudio.duration <= myAudio.currentTime + 0.5) {
            console.log("audio ended timeupdate");
            console.log(e);
            return this.onended();
          }
          this.$store.state.audioCurrentTime = myAudio.currentTime;
        });
        myAudio.addEventListener("pause", (e) => {
          console.log("pause");
          this.$store.state.isAudioPause = true;
          setTimeout(() => {
            if (this.$route.name === "videoDetail") {
              window.audioPlayer.back();
            }
          }, 10);
        });
        myAudio.addEventListener("play", (e) => {
          console.log("audio play");
          this.$store.state.isAudioPause = false;
          this.showAudio();
        });
      }
    },
    showAudio() {
      console.log("showAudio");
      window.audioPlayer.setUrl(this.getVideoSrc(this.detail));
      window.audioPlayer.setContentId(this.detail.newsContent.id);
      window.audioPlayer.setTitle(this.preData.title);
      setTimeout(() => {
        let myAudio = document.getElementById("myAudio");
        myAudio.play();
        this.listenAudio();
      }, 1000);
    },
    getPoster(item) {
      if(item.newsContent && this.tools.indexOfHttp(item.newsContent.listPicUrl)){
        return item.newsContent.listPicUrl
      }
      return this.tools.getImgUrl(item.newsContent && item.newsContent.listPic);
    },
    getVideoSrc(item) {
      if(item.files && item.files.length>0 && item.files[0].fileOssUrl && this.tools.indexOfHttp(item.files[0].fileOssUrl)){
        return item.files[0].fileOssUrl
      }
      if (
        item.newsContent &&
        item.newsContent.videoUrl &&
        item.newsContent.videoUrl !== ""
      ) {
        return item.newsContent.videoUrl;
      }
      return this.tools.getImgUrl(item.files && item.files[0].fileId);
    },
    up() {
      let params = {
        contentId: this.preData.id,
        type: 1,
      };
      return this.fetchService.newsUpsAndDowns(params).then((res) => {
        if (res.code !== 0) {
          return this.tools.tip(res.message || "接口服务出错，请联系管理员");
        }
        this.preData.ups++;
        this.tools.tip("点赞成功");
        return res;
      });
    },
    updateCount() {
      let id = this.preData.id;
      let params = {
        contentId: id,
        type: 1,
      };
      this.fetchService.updateCount(params).then((res) => {
        if (res.code !== 0) {
          return false;
        }
      });
    },
    //获取内容详情(新)
    contentDetailNew(id) {
      let me = this;
      return me.fetchService.contentDetailNew(id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    //获取新闻附件
    newsFiles(id) {
      let me = this;
      return me.fetchService.newsFiles(id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    //查询当前用户是否点赞指定的新闻
    contentGetSfdz(id) {
      let me = this;
      return me.fetchService.contentGetSfdz(id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    //查询当前用户是否收藏指定的新闻
    contentGetSfsc(id) {
      let me = this;
      return me.fetchService.contentGetSfsc(id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    loadData() {
      var id = this.$route.query.id;

      var me = this;
      return Axios.all([
        me.contentDetailNew(id),
        me.newsFiles(id),
        me.contentGetSfdz(id),
        me.contentGetSfsc(id),
      ])
        .then(
          Axios.spread((res1, res2, res3, res4) => {
            me.detail = res1;
            me.detail.files = res2;
            me.detail.upOrDown = res3;
            me.detail.collected = res4;


            if (this.detail.newsContentExt) {
              this.historyAdd() // 添加到我的足迹
            }

            me.$store.state.newsDetail = _.extend(
              me.$store.state.newsDetail,
              me.detail.newsContent
            );
            me.$store.state.newsDetail.detail = me.detail;
            console.log(
              "me.$store.state.newsDetail",
              me.$store.state.newsDetail
            );
            me.log();
            me.play(me.detail);
            me.addViews(id);
            if (!me.$store.state.isVideo) {
              me.showAudio();
            }
          })
        )
        .catch((err) => {
          console.log(err.response);
        });

      /* this.fetchService.contentPageDetail(id).then((res) => {
        if (res.code !== 0) {
          return false;
        }
        this.detail = res.data;
        this.$store.state.newsDetail = _.extend(
          this.$store.state.newsDetail,
          this.detail.newsContent
        );
        this.$store.state.newsDetail.detail = this.detail;
        //          ++this.$store.state.newsDetail.views
        console.log('this.$store.state.newsDetail',this.$store.state.newsDetail)
        this.log();
        this.play(this.detail);
        this.addViews(id);
        if (!this.$store.state.isVideo) {
          this.showAudio();
        }
      }); */
    },
    addViews(id) {
      this.audioList.findIndex((item) => {
        if (item.id === id) {
          ++item.views;
        }
      });
    },
    /*阿里播放器*/
    aliplay(data) {
      var player = new Aliplayer(
        {
          id: "videoPlayer",
          source: this.getVideoSrc(data),
          preload: true,
          autoplay: true,
          rePlay: true,
          controlBarVisibility: "click",
          showBarTime: "3000",
          x5_type: "h5",
          x5_fullscreen: true,
          height: "100%",
        },
        function (player) {
          $("#videoPlayer video").attr("poster","static/images/dangjian/video/backgroud-poster.png")
          player.play();
        }
      );
      $('.prism-error-operation').hide();
      $('.prism-error-content p').hide();
      $('.prism-error-content').append('<p style="margin-top: 50px;">播放出错啦！</p>');
      this.videoPlayerEvent(player);
    },
    play(data) {
      let me = this;
      let id = this.$route.query.id;
      /* return new Player({
          id: 'videoPlayer',
          url: this.getVideoSrc(data),
          fluid: true,
          poster: this.getPoster(data)
        })*/
      if (this.$store.state.isVideo) {
        if (TEST) {
          this.aliplay(data);
          return;
        }
        let player = new Player({
          id: "videoPlayer",
          url: this.getVideoSrc(data),
          autoplay: true,
          fluid: true,
          //            cssFullscreen: true,
          rotate: {
            //视频旋转按钮配置项
            innerRotate: true, //只旋转内部video
            clockwise: false, // 旋转方向是否为顺时针
          },
          poster: this.getPoster(data),
        });
        player.back = function (type) {
          if (type === undefined) {
            player.exitFullscreen();
          } else if (type === "exitFullscreen") {
            // 通过事件退出
          }
          if (me.isFullScreen) {
            me.isFullScreen = false;
            player.rotate(true, true, -1);
          }
          if (me.tools.getDialogNum() > 0) {
            me.tools.dialog(-1);
          }
          if (me.tools.getDialogNum() <= 0) {
            me.tools.dialogDestroy();
          }
        };
        player.on("ended", () => {
          console.log("video ended");
          this.onended();
          this.$localStorage.set("videoPlayTime" + id, 0);
        });
        player.on("requestFullscreen", () => {
          player.rotate(true, true, 1);
          console.log("video requestFullscreen");
          this.tools.dialog(1, player);
        });
        player.on("exitFullscreen", () => {
          console.log("video ");
          player.back("exitFuexitFullscreenllscreen");
        });
        player.on("rotate", (deg) => {
          this.rotateDeg = deg;
          console.log(deg);
        });
        player.on("play", () => {
          let videoPlayTime = this.$localStorage.get("videoPlayTime" + id);
          console.log("play", videoPlayTime, player.currentTime);
          if (videoPlayTime) {
            player.currentTime = videoPlayTime;
          }
        });
        // 检查是否全屏
        function checkFullScreen() {
          let playerDom = document.getElementById("videoPlayer");
          if (domUtils.hasClass(playerDom, "xgplayer-is-fullscreen")) {
            onFullScreen();
            if (
              !domUtils.hasStyle(
                document.getElementsByTagName("video")[0],
                "rotate(0.25turn"
              )
            ) {
              player.rotate(true, true, 1);
            }
          } else {
            if (
              !domUtils.hasStyle(
                document.getElementsByTagName("video")[0],
                "rotate(0turn)"
              )
            ) {
              player.rotate(true, true, -1);
            }
          }
        }

        this.checkPlayerTimer = setInterval(checkFullScreen, 500);
        // 固定是否有
        // 全屏标记
        let me = this;

        function onFullScreen() {
          if (me.tools.getDialogNum() <= 0) {
            this.tools.dialog(1, player);
            me.isFullScreen = true;
          }
        }

        let consoleTime = Date.now();
        player.on("timeupdate", () => {
          //            checkFullScreen()
          if (Date.now() - consoleTime > 3 * 1000) {
            console.log("timeupdate", player.currentTime);
            consoleTime = Date.now();
            this.$localStorage.set("videoPlayTime" + id, player.currentTime);
          }
        });
        $('.prism-error-operation').hide();

      }
    },
    /*阿里播放的事件、方法*/
    videoPlayerEvent(player) {
      let me = this;
      let id = this.$route.query.id;
      player.on("ended", () => {
        console.log("video ended");
        this.onended();
        this.$localStorage.set("videoPlayTime" + id, 0);
      });
      player.on("requestFullscreen", () => {
        player.rotate(true, true, 1);
        console.log("video requestFullscreen");
        this.tools.dialog(1, player);
      });
      player.on("exitFullscreen", () => {
        console.log("video ");
        player.back("exitFuexitFullscreenllscreen");
      });
      player.on("rotate", (deg) => {
        this.rotateDeg = deg;
        console.log(deg);
      });
      player.on("play", () => {
        let videoPlayTime = this.$localStorage.get("videoPlayTime" + id);
        console.log("play", videoPlayTime, player.getCurrentTime());
        if (videoPlayTime) {
          player.seek(videoPlayTime);
        }
      });
      let consoleTime = Date.now();
      player.on("timeupdate", () => {
        //            checkFullScreen()
        if (Date.now() - consoleTime > 3 * 1000) {
          console.log("timeupdate", player.getCurrentTime());
          consoleTime = Date.now();
          this.$localStorage.set("videoPlayTime" + id, player.getCurrentTime());
        }
      });
      player.on("requestFullScreen", () => {
        console.log("---------------------requestFullScreen--------");
        if (!window.webkit) {
          console.log("requestFullScreen");
          // document.querySelector('#videoPlayer').className += ' video-player'
          // player.setRotate(90)
          if (window.android && window.android.screenToggle) {
            window.android.screenToggle(1);
          }
        }
        console.log(this.$router);
        this.$store.state.hasFullScreen = true;
        this.$router.options.routes.forEach((v) => {
          if (v.name === "redCloudHeadline") {
            v.meta.keepAlive = true;
          }
        });
      });
      player.on("cancelFullScreen", () => {
        console.log("---------------------cancelFullScreen--------");
        if (window.android && window.android.screenToggle) {
          window.android.screenToggle(2);
        }
        try {
          let className = document.querySelector("#videoPlayer").className;
          className = className.replace(/\svideo-player/g, "");
          document.querySelector("#videoPlayer").className = className;
        } catch (e) {
          console.log("报错：" + e);
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.video-page {
  position: relative;
  .header-wrap-wrap {
    position: absolute;
    z-index: 1;
  }
}
.m-content {
  padding: 0 0 0 .26667rem;
  font-size: 14PX;
  font-family: PingFang SC,miui,system-ui,-apple-system,BlinkMacSystemFont,Helvetica Neue,Helvetica,sans-serif;
  &.overflow-line {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    word-break: break-all;
  }
}
.btn-more {
  color: #5383E7;
  position: relative;
  display: flex;
  padding: 0 0 0 .26667rem;
  font-size: 14PX;
  justify-content: flex-end;
  &.more-collapse {

    &::after,
    &::before {
      top: 2px;
      transform: rotate(180deg);
    }

    &::before {
      top: 4px;
    }
  }

  &::after,
  &::before {
    width: 0;
    height: 0;
    content: '';
    position: absolute;
    right: 0;
    top: 7px;
    border: rc(12) solid transparent;
  }

  &::after {
    border-top-color:#5383E7;
    z-index: 1;
  }

  &::before {
    border-top-color: #1c2239;
    z-index: 2;
    top: 5px;
  }

}
.video {
  position: relative;
  z-index: 0;
  height: 420px;
  text-align: center;
  background: #000;
  video {
    width: 100vw;
    height: 100%;
    margin: 0 auto;
  }
  .audio {
    background: #8a7575;
    width: 100%;
    .audio-self {
      background: #fff;
    }
    audio {
      width: 100%;
    }
    .audio-img {
      height: 300px;
    }
  }
}
.water-logo {
  text-align: center;
  padding: 50px;
  img {
    opacity: 0.6;
  }
}
.detail {
  .date {
    display:flex;
    white-space: nowrap;
    flex-wrap: wrap;
    .flex-1 {
      flex:1;
      white-space: nowrap;
    }
    .float-right {
      float: none;
      white-space: nowrap;
    }
  }
}
</style>
